import { Handler } from "../../../app_base/base/utils/Handler";
import { ILoginAble } from "../../../app_base/module/publisher/ILoginAble";
import { app } from "../../../base";

const tt = window['tt'];
const LoginAPI = "https://api.game.hnquyou.com/api/game-common/user/login";
export class TTLoginHelper extends ILoginAble {
    private _openId: string;
    login(caller?: any, onSuccess?: () => void, onFail?: () => void): void {
        tt.login({
            force: true,
            success: (res: { errMsg: string, code: string, isLogin: boolean, anonymousCode: string }) => {
                console.log(`tt.login 调用成功${res.code} ${res.anonymousCode}`);
                app.net.http.post(LoginAPI, {
                    data: {
                        appid: app.publisher.appId,
                        code: res.code,
                        anonymousCode: res.anonymousCode
                    },
                    onComplete: Handler.create(this, (serverData) => {
                        console.log("openid获取成功:", serverData);
                        if (typeof serverData == 'string' && serverData.length > 0) {
                            serverData = JSON.parse(serverData)
                        }
                        let resData = serverData.data;
                        if (resData) {
                            this._openId = resData.openid || resData.anonymousOpenid;

                            onSuccess && onSuccess.apply(caller);
                        } else {
                            onFail.apply(caller);
                        }
                    })
                })
            },
            fail(res) {
                onFail && onFail.apply(caller);
            },
        });
    }

    get openID(): string {
        return this._openId;
    }
}